package com.xzc._3_running;

import com.xzc._1_build.Base_Test;
import lombok.Data;
import org.drools.core.test.model.Cheese;
import org.kie.api.KieBase;
import org.kie.api.command.Command;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.internal.command.CommandFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 命令执行器，可以获得全局变量的值
 */
@Data
public class CommandExecutor {
    Base_Test t = new Base_Test();
    KieBase kbase;
    KieSession ksession;

    public void init() {
        t.createContainerByClasspath();
        KieBase kbase = t.getKieContainer().getKieBase("KBase1");
        KieSession ksession = t.getKieContainer().newKieSession("KSession2_1");
    }

    /**
     * 执行命令，一般用于操作Global变量
     * 第3个参数为true就会用第一个参数为key，返回第2个参数
     * 如果已经存在了key，就会修改这个Global变量
     * StatelessKieSession在命令执行完，session销毁时会执行fireAllRules()
     */
    public void setGlobalInExecutionResults() {
        StatelessKieSession ksession = kbase.newStatelessKieSession();
        ExecutionResults bresults =
                ksession.execute((Command<ExecutionResults>) CommandFactory.newSetGlobal("stilton", new Cheese("stilton", 1), true));
        Cheese stilton = (Cheese) bresults.getValue("stilton");
    }

    /*
    * 执行命令，获取Global变量
     */
    public void getGlobalInExecutionResults() {
        StatelessKieSession ksession = kbase.newStatelessKieSession();
        ExecutionResults bresults =
                ksession.execute((Command<ExecutionResults>) CommandFactory.newGetGlobal("stilton"));
        Cheese stilton = (Cheese) bresults.getValue("stilton");
    }

    /**
     * 批量提交命令，每一个命令执行会将结果写入到ExecutionResults中
     */
    public void batchExecutionCommands() {
        StatelessKieSession ksession = kbase.newStatelessKieSession();

        List cmds = new ArrayList();
        cmds.add(CommandFactory.newInsert(new Cheese("stilton", 1), "stilton"));
        cmds.add(CommandFactory.newStartProcess("process cheeses"));
        cmds.add(CommandFactory.newQuery("stilton", "stilton"));
        ExecutionResults bresults = ksession.execute(CommandFactory.newBatchExecution(cmds));
        Cheese stilton = (Cheese) bresults.getValue("stilton");
        QueryResults qresults = (QueryResults) bresults.getValue("cheeses");
    }
}
